<?php

namespace app\admin\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;
use think\Request;
use think\Queue;

header('Content-Type: text/html; charset=utf-8');

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('mini_menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    public function test()
    {
        return $this->view->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }

    /**
     * 文章分类列表
     * */
    public function articleTypeList()
    {
        $list = Db::name('mini_article_type')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章分类
     * */
    public function doArticleType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('mini_article_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name
            ];

            if ($id > 0) {
                $res = Db::name('mini_article_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('mini_article_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '新增文章分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('mini_article_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '文章分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章分类
     * */
    public function delArticleType()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '分类ID缺失');

        $info = Db::name('mini_article_type')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('mini_article_type')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        if ($title) $where['title'] = ['like', '%' . $title . '%'];

        $list = Db::name('mini_article')->where($where)->order('sort asc, id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $content = $input['content'];

            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($content)) adminReturn(2, '请输入内容');

            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('mini_article')->where(['title' => $title])->where($where)->count();
            if ($count) adminReturn(2, '文章标题已存在');

            $time = time();
            $data = [
                'title' => $title,
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('mini_article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('mini_article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('mini_article')->where(['id' => $id])->find();
            }

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('mini_article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('mini_article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 提现列表
     * */
    public function withdrawalList()
    {
        $input = Request()->param();

        $list = Db::table('fa_user_withdraw')->where('from', 2)->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '提现列表');

        return $this->view->fetch();
    }

    /**
     * 通过
     * */
    public function agreeWithdrawal()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::table('fa_user_withdraw')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '数据不存在或已删除');

        $res = Db::table('fa_user_withdraw')->where(['id' => $id])->update(['status' => 1, 'checktime' => time()]);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 打款
     * */
    public function payWithdrawal()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::table('fa_user_withdraw')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '数据不存在或已删除');

        $res = Db::table('fa_user_withdraw')->where(['id' => $id])->update(['status' => 2, 'checktime' => time(), 'paytime' => time()]);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 驳回
     * */
    public function refuseWithdrawal()
    {
        $input = Request()->param();

        $id = $input['id'];
        $note = $input['note'];

        if (empty($id)) adminReturn(2, 'ID缺失');
        if (empty($note)) adminReturn(2, '请输入驳回原因');

        $info = Db::table('fa_user_withdraw')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '数据不存在或已删除');

        $user_info = Db::table('fa_user')->where('id', $info['user_id'])->find();
        if (empty($user_info)) adminReturn(2, '用户不存在');

        $time = time();

        Db::startTrans();
        try {
            Db::table('fa_user')->where('id', $info['user_id'])->setInc('money', $info['money']);

            Db::table('fa_user_withdraw')->where('id', $id)->update(['status' => 3, 'note' => $note, 'checktime' => $time]);

            $log_data = [
                'user_id' => $info['user_id'],
                'money' => $info['money'],
                'before' => $user_info['money'],
                'after' => $user_info['money'] + $info['money'],
                'type' => 4,
                'remark' => '提现申请被驳回',
                'create_time' => $time,
                'link_id' => $id,
                'link_table' => 'fa_user_withdraw',
                'from' => 2
            ];
            Db::name('mini_user_money_log')->insert($log_data);

            Db::commit();
            adminReturn(1, '操作成功');
        } catch (Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败' . $e->getMessage());
        }
    }


    /**
     * 规格-属性 列表
     * */
    public function skuList()
    {
        $list = Db::name('mini_sku')->select();
        $this->assign('list', json_encode($list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '规格-属性');
        return $this->fetch();
    }

    /**
     * 新增/编辑 规格-属性
     * */
    public function doSku()
    {

        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $pid = $input['pid'];
            $name = $input['name'];

            if (empty($name)) apiReturn(2, '请输入名称');

            if ($id) {
                $where['name'] = $name;
                $where['id'] = ['neq', $id];
                if ($pid) {
                    $where['pid'] = $pid;
                } else {
                    $where['pid'] = 0;
                }
                $count = Db::name('mini_sku')->where($where)->count();

                $obj = $pid ? '属性' : '规格';
                if ($count > 0) apiReturn(2, '该' . $obj . '名称已存在');

                //编辑
                $data = [
                    'name' => $name,
                    'pid' => $pid,
                ];

                $res = Db::name('mini_sku')->where(['id' => $id])->cache('sku')->update($data);
                if ($res) {
                    apiReturn(1, '编辑成功');
                } else {
                    apiReturn(2, '编辑失败');
                }
            } else {
                $where['name'] = $name;
                if ($pid) {
                    $where['pid'] = $pid;
                } else {
                    $where['pid'] = 0;
                }

                $count = Db::name('mini_sku')->where($where)->count();

                $obj = $pid ? '属性' : '规格';
                if ($count > 0) apiReturn(2, '该' . $obj . '名称已存在');

                //新增
                $data = [
                    'name' => $name,
                    'pid' => $pid,
                ];

                $res = Db::name('mini_sku')->insert($data);
                if ($res) {
                    cache('sku', null);
                    apiReturn(1, '新增成功');
                } else {
                    apiReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('mini_sku')->where(['id' => $id])->find();
            } else {
                $info = [];
            }

            $sku_list = Db::name('mini_sku')->where(['pid' => 0])->select();

            $data = [
                'info' => $info,
                'sku_list' => $sku_list
            ];

            apiReturn(1, '获取数据成功', $data);
        }

    }

    /**
     * 删除 规格-属性
     * */
    public function delSku()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        $obj = $pid ? '属性' : '规格';
        if (empty($id)) apiReturn(2, $obj . 'ID缺失');

        Db::startTrans();
        try {
            Db::name('mini_sku')->where(['id' => $id])->cache('sku')->delete();
            if ($pid == 0) Db::name('mini_sku')->where(['pid' => $id])->delete();

            Db::commit();
            apiReturn(1, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 商品分类列表
     * */
    public function goodsTypeList()
    {
        $list = Db::name('mini_goods_type')->order('id asc')->select();

        $this->assign('list', $list);
        $this->assign('title', '商品分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 商品分类
     * */
    public function doGoodsType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('mini_goods_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name,
            ];

            if ($id > 0) {
                $res = Db::name('mini_goods_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑商品分类成功', url('goodsTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('mini_goods_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增商品分类成功', url('goodsTypeList'));
                } else {
                    adminReturn(2, '新增商品分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('mini_goods_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '商品分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除商品分类
     * */
    public function delGoodsType()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        if (empty($id)) adminReturn(2, '分类ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('mini_goods_type')->where(['id' => $id])->find();
            if ($info) {
                Db::name('mini_goods_type')->where(['id' => $id])->delete();
                if ($pid == 0) Db::name('mini_goods_type')->where(['pid' => $id])->delete();

                Db::commit();
                adminReturn(1, '删除成功');
            } else {
                Db::rollback();
                adminReturn(2, '数据不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试~');
        }
    }


    /**
     * 网站配置排序
     * */
    public function saveGoodsTypeSort()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('MiniGoodsType')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 运费模板
     * */
    public function freightList()
    {
        $list = Db::name('mini_freight')->paginate();


        $this->assign('list', $list);
        $this->assign('title', '运费模板');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 运费模板
     * */
    public function doFreight()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $type = $input['type'];
            $init_count = $input['init_count'];
            $init_count_price = $input['init_count_price'];
            $inc_count = $input['inc_count'];
            $inc_count_price = $input['inc_count_price'];
            $init_weight = $input['init_weight'];
            $init_weight_price = $input['init_weight_price'];
            $inc_weight = $input['inc_weight'];
            $inc_weight_price = $input['inc_weight_price'];
            $diff_freight = $input['diff_freight'];

            if (empty($name)) apiReturn(2, '请输入模板名称');

            $where['name'] = $name;
            if ($id > 0) $where['id'] = ['neq', $id];
            $count = Db::name('mini_freight')->where($where)->count();
            if ($count > 0) adminReturn(2, '模板名称已存在');


            if (($type == 1 && (empty($init_count) || empty($init_count_price) || empty($inc_count) || empty($inc_count_price)))
                ||
                ($type == 2 && (empty($init_weight) || empty($init_weight_price) || empty($inc_weight) || empty($inc_weight_price)))
            ) adminReturn(2, '请完善计价规格');

            $time = time();
            $data = [
                'name' => $name,
                'type' => $type,
                'init_count' => $init_count,
                'init_count_price' => $init_count_price,
                'inc_count' => $inc_count,
                'inc_count_price' => $inc_count_price,
                'init_weight' => $init_weight,
                'init_weight_price' => $init_weight_price,
                'inc_weight' => $inc_weight,
                'inc_weight_price' => $inc_weight_price,
                'diff_freight' => $diff_freight,
            ];

            if ($id > 0) {
                // 编辑
                $data['update_time'] = $time;
                $res = Db::name('mini_freight')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('freightList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                // 新增
                $data['create_time'] = $time;
                $res = Db::name('mini_freight')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('freightList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('mini_freight')->where(['id' => $id])->find();

            $province_list = Db::name('mini_province')->field('province_id,name province_name')->select();
            if ($province_list) {
                foreach ($province_list as &$v) {
                    $city_list = Db::name('mini_city')->field('city_id,name city_name')->where(['province_id' => $v['province_id']])->select();
                    $v['city_list'] = $city_list;
                }
            }

            $info['diff_freight_list'] = json_decode($info['diff_freight'], true);
            $this->assign('diff_freight_data', $info['diff_freight'] ? $info['diff_freight'] : json_encode([]));
            $this->assign('info', $info);
            $this->assign('province_list', $province_list);
            $this->assign('title', ($id ? '编辑' : '新增') . '运费模板');
            return $this->view->fetch();
        }
    }

    /**
     * 服务保障
     * */
    public function serviceGuarantee()
    {
        if (Request()->isPost()) {
            $service_guarantee = Request()->param('service_guarantee');

            $res = Db::name('mini_goods_service_guarantee')->where(' 1 = 1 ')->setField(['service_guarantee' => $service_guarantee]);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $service_guarantee = Db::name('mini_goods_service_guarantee')->value('service_guarantee');

            $this->assign('service_guarantee', json_decode($service_guarantee, true));
            $this->assign('title', '服务保障');
            return $this->view->fetch();
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $one_type_id = $input['one_type_id'];
        $upper = $input['upper'];

        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($upper) $where['upper'] = $upper;

        $list = Db::name('mini_goods')->where($where)->order('create_time desc')->paginate()->each(function ($item) {
            $item['one_type_name'] = Db::name('mini_goods_type')->where(['id' => $item['one_type_id']])->value('name');

            return $item;
        });
        $this->assign('list', $list);

        $type_list = Db::name('mini_goods_type')->select();
        $this->assign('type_list', $type_list);

        $this->assign('title', '商品列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 商品
     * */
    public function doGoods()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            Db::startTrans();
            try {
                //参数处理
                parse_str($input['form'], $form);

                $price_arr = [];
                if ($form['skus']) {
                    foreach ($form['skus'] as $v) {
                        if ($v['status'] == 1) $price_arr[] = $v['price'];
                    }
                }

                $min_price = min($price_arr);
                $max_price = max($price_arr);

                $use_coupon_price_arr = [];
                if ($form['skus']) {
                    foreach ($form['skus'] as $v) {
                        if ($v['status'] == 1) $use_coupon_price_arr[] = $v['use_coupon_price'];
                    }
                }

                $min_use_coupon_price = min($use_coupon_price_arr);
                $max_use_coupon_price = max($use_coupon_price_arr);

                $skus = $form['skus'];

                $id = $form['id'];

                if (empty($form['name'])) adminReturn(2, '请输入商品名称');
                if (empty($form['img'])) adminReturn(2, '请上传封面图');
                if (empty($form['one_type_id'])) adminReturn(2, '请选择所属分类');
                //                if (empty($form['content'])) adminReturn(2, '请输入商品介绍');
                $time = time();

                if ($skus) {
                    foreach ($skus as $v) {
                        if ($v['price'] <= 0) adminReturn(2, '请完善销售价');
                        if ($v['use_coupon_price'] <= 0 && $form['one_type_id'] == 2) adminReturn(2, '请完善券抵扣价');
                    }
                }
                unset($form['skus']);

                $sort_ids = $input['sort_ids'];
                if ($sort_ids) {
                    Db::name('mini_goods_sku')->where(['id' => ['IN', $sort_ids]])->setField('sort', 0);
                    $sort_ids_arr = explode(',', $sort_ids);
                    foreach ($sort_ids_arr as $k => $v) {
                        Db::name('mini_goods_sku')->where(['id' => $v])->setField('sort', $k + 1);
                    }
                }

                $data = [
                    'name' => $form['name'],
                    'img' => $form['img'],
                    'imgs' => $form['imgs'],
                    'one_type_id' => $form['one_type_id'],
                    'skus' => $input['skus'],
                    'min_price' => $min_price >= 0 ? $min_price : 0,
                    'max_price' => $max_price >= 0 ? $max_price : 0,
                    'min_use_coupon_price' => $min_use_coupon_price >= 0 ? $min_use_coupon_price : 0,
                    'max_use_coupon_price' => $max_use_coupon_price >= 0 ? $max_use_coupon_price : 0,
                    'upper' => $form['upper'],
                    'is_hot' => $form['is_hot'],
                    'is_recommend' => $form['is_recommend'],
                    'bv' => $form['bv'],
                    'team_user_id' => $form['team_user_id'],
                    'benefit_direct' => $form['benefit_direct'],
                    'benefit_v1' => $form['benefit_v1'],
                    'benefit_v2' => $form['benefit_v2'],
                    'benefit_v3' => $form['benefit_v3'],
                    'benefit_v4' => $form['benefit_v4'],
                    'benefit_v5' => $form['benefit_v5'],
                    'benefit_v6' => $form['benefit_v6'],
                    'content' => $form['content'],
                    'sku_key' => $input['sku_key']
                ];

                if ($id > 0) {
                    //编辑
                    $data['update_time'] = $time;

                    Db::name('mini_goods')->where(['id' => $id])->update($data);

                    Db::name('mini_sku_value')->where(['goods_id' => $id])->delete();

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $id;

                            if ($v['picture']) {
                                $picture_info = Db::name('mini_picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('mini_sku_value')->insertAll($sku_value);
                    }

                    Db::commit();
                    adminReturn(1, '编辑商品成功', url('goodsList'));
                } else {
                    //新增
                    $data['create_time'] = $time;

                    $goods_id = Db::name('mini_goods')->insertGetId($data);

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $goods_id;

                            if ($v['picture']) {
                                $picture_info = Db::name('mini_picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('mini_sku_value')->insertAll($sku_value);
                    }

                    Db::commit();
                    adminReturn(1, '新增商品成功', url('goodsList'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~' . $e);
            }
        } else {
            $id = Request()->param('id');

            $info = Db::name('mini_goods')->where(['id' => $id])->find();
            $info['imgs_arr'] = doImgs($info['imgs']);

            $this->assign('title', $id ? '编辑商品' : '新增商品');

            // 商品sku唯一标识
            if ($info['sku_key']) {
                $sku_key = $info['sku_key'];
            } else {
                $sku_key = uniqid();

                $parent_sku_list = Db::name('mini_sku')->where(['pid' => 0])->order('id asc')->select();
                if ($parent_sku_list) {
                    foreach ($parent_sku_list as $v) {
                        $parent_sku_data = [
                            'name' => $v['name'],
                            'sku_key' => $sku_key
                        ];
                        $pid = Db::name('mini_goods_sku')->insertGetId($parent_sku_data);

                        $son_sku_list = Db::name('mini_sku')->where(['pid' => $v['id']])->order('id asc')->select();
                        if ($son_sku_list) {
                            $son_sku_data = [];
                            foreach ($son_sku_list as &$val) {
                                $son_sku_data[] = [
                                    'pid' => $pid,
                                    'name' => $val['name'],
                                    'sku_key' => $sku_key
                                ];
                            }
                            Db::name('mini_goods_sku')->insertAll($son_sku_data);
                        }
                    }
                }
            }
            $this->assign('sku_key', $sku_key);

            $sku_list = Db::name('mini_goods_sku')->field('id,name title')->where(['sku_key' => $sku_key, 'pid' => 0])->order('sort asc')->select();
            if ($sku_list) {
                //$skus_id_arr：所有属性的id集合
                $skus_id_arr = [];

                foreach ($sku_list as &$v) {
                    if ($id > 0) {
                        $sku_value_list = Db::name('mini_sku_value')->field('sku_id')->where(['goods_id' => $id])->select();

                        if ($sku_value_list) {
                            foreach ($sku_value_list as &$val) {
                                $sku_id = explode('-', $val['sku_id']);
                                if ($sku_id) {
                                    foreach ($sku_id as &$value) {
                                        if (!in_array($value, $skus_id_arr)) {
                                            $skus_id_arr[] = $value;
                                        }
                                    }
                                }
                            }
                        }

                        $parent_list = Db::name('mini_goods_sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr], 'sku_key' => $sku_key])->select();
                        $parent_ids = array_column($parent_list, 'pid');

                        $v['checked'] = false;
                        if (in_array($v['id'], $parent_ids)) $v['checked'] = true;
                    } else {
                        $v['checked'] = false;
                    }

                    $child = Db::name('mini_goods_sku')->field('id,name title')->where(['pid' => $v['id'], 'sku_key' => $sku_key])->select();
                    if ($child) {
                        foreach ($child as &$val) {
                            $val['checked'] = in_array($val['id'], $skus_id_arr) ? true : false;
                        }
                    }
                    $v['child'] = $child;
                }
            }

            $this->assign('id', $id ? : 0);
            $this->assign('bv', C('BV'));
            $this->assign('benefit_direct', C('BENEFIT_DIRECT'));
            $this->assign('benefit_v1', C('BENEFIT_V1'));
            $this->assign('benefit_v2', C('BENEFIT_V2'));
            $this->assign('benefit_v3', C('BENEFIT_V3'));
            $this->assign('benefit_v4', C('BENEFIT_V4'));
            $this->assign('benefit_v5', C('BENEFIT_V5'));
            $this->assign('benefit_v6', C('BENEFIT_V6'));

            $type_list = Db::name('mini_goods_type')->select();
            $this->assign('type_list', $type_list);

            $user_list = Db::table('fa_user')->field('id,unique_id,mobile,team_count')->select();
            $this->assign('user_list', $user_list);


            $this->assign('info', $info);
            $this->assign('type', $info['one_type_id']);
            $this->assign('sku_list', json_encode($sku_list, JSON_UNESCAPED_UNICODE));
            return $this->fetch();
        }
    }

    /**
     * 删除商品
     * */
    public function delGoods()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '商品ID缺失');

        $info = Db::name('mini_goods')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('mini_goods')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 套餐列表
     */
    public function mealList()
    {
        $list = Db::name('meal')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '套餐列表');

        return $this->view->fetch();
    }


    /**
     * 新增/编辑 套餐
     * */
    public function doMeal()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $imgs = $input["imgs"];
            $name = $input["name"];
            $price = $input['price'];
            $main_goods_name = $input["main_goods_name"];
            $main_goods_count = $input["main_goods_count"];
            $valid_day = $input["valid_day"];
            $main_goods_integral = $input["main_goods_integral"];
            $minor_goods_name = $input["minor_goods_name"];
            $minor_goods_integral = $input["minor_goods_integral"];
            $minor_get_cycle = $input["minor_get_cycle"];
            $minor_get_day = $input["minor_get_day"];
            $minor_get_count = $input["minor_get_count"];
            $upper = $input["upper"];
            $content = $input["content"];


            if (empty($img)) adminReturn(2, "请上传封面图");
            if (empty($imgs)) adminReturn(2, "请上传轮播图");
            if (empty($name)) adminReturn(2, "请输入券名称");
            if (empty($price)) adminReturn(2, "请输入价格");
            if (empty($main_goods_name)) adminReturn(2, "请输入主产品名称");
            if (empty($main_goods_count)) adminReturn(2, "请输入主产品数量");
            if (empty($valid_day)) adminReturn(2, "请输入有效期（天）");
            if (empty($main_goods_integral)) adminReturn(2, "请输入单个主产品可兑换积分");
            if (empty($minor_goods_name)) adminReturn(2, "请输入赠品名称");
            if (empty($minor_goods_integral)) adminReturn(2, "请输入单个赠品可兑换积分");
            if (empty($minor_get_day)) adminReturn(2, "请输入赠品领取周期（天）");
            if (empty($minor_get_cycle) || $minor_get_cycle <= 0) adminReturn(2, "请输入赠品领取期数");
            if (empty($minor_get_count) || $minor_get_count <= 0) adminReturn(2, "请输入赠品周期领取数量");

            $data = [
                "img" => $img,
                "imgs" => $imgs,
                "name" => $name,
                "price" => $price,
                "main_goods_name" => $main_goods_name,
                "main_goods_count" => $main_goods_count,
                "main_goods_integral" => $main_goods_integral,
                "valid_day" => $valid_day,
                "minor_goods_name" => $minor_goods_name,
                "minor_goods_count" => $minor_get_count * $minor_get_cycle,
                "minor_goods_integral" => $minor_goods_integral,
                "minor_get_day" => $minor_get_day,
                "minor_get_cycle" => $minor_get_cycle,
                "minor_get_count" => $minor_get_count,
                "upper" => $upper,
                "content" => $content
            ];

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('meal')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('mealList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data["create_time"] = time();
                $res = Db::name('meal')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('mealList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('meal')->where(['id' => $id])->find();
            $info['imgs_arr'] = doImgs($info['imgs']);

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '套餐');

            return $this->view->fetch();
        }
    }

    /**
     * 设置充值
     * */
    public function setRecharge()
    {
        if (Request()->isPost()) {
            $recharge_guarantee = Request()->param('recharge_guarantee');

            $res = Db::name('mini_recharge_guarantee')->where(' 1 = 1 ')->setField(['recharge_guarantee' => $recharge_guarantee]);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $recharge_guarantee = Db::name('mini_recharge_guarantee')->value('recharge_guarantee');

            $this->assign('recharge_guarantee', json_decode($recharge_guarantee, true));
            $this->assign('title', '设置充值');
            return $this->view->fetch();
        }
    }


    /**
     * 领取记录
     * */
    public function receiveList()
    {
        $input = Request()->param();

        $status_code = $input['status_code'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $user_id = $input['user_id'];

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        if ($user_id) $where['a.user_id'] = $user_id;

        $where['a.type'] = 2;

        $list = Db::name('meal_consume a')->join('mini_user b', "a.user_id = b.id", "left")
            ->field("a.*,b.mobile,b.username")
            ->where($where)->order('create_time desc')
            ->paginate()->each(
                function ($v) {
                    if ($v['pay_type'] == 1) {
                        $v['pay_type_text'] = "微信支付";
                    } elseif ($v['pay_type'] == 2) {
                        $v['pay_type_text'] = "余额支付";
                    } else {
                        $v['pay_type_text'] = "未知";
                    }

                    return $v;
                }
            );
        $this->assign('list', $list);

        $all_pay_price = Db::name('mini_order a')->join('mini_user b', "a.user_id = b.id", "left")->where($where)->sum('pay_price');
        $this->assign('all_pay_price', sprintf('%.2f', $all_pay_price));

        $user_list = Db::name('mini_user')->where(['is_admin' => 0, 'status' => 1])->select();
        $this->assign('user_list', $user_list);

        $this->assign('title', '领取记录');

        return $this->fetch();
    }

    /**
     * 优惠券设置
     */
    public function couponList()
    {
        $input = Request()->param();

        $name = $input['name'];
        $where["id"] = ["gt", 0];
        if ($name) $where['name'] = ["like", '%' . $name . '%'];
        $list = Db::name('mini_coupon')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '满减券列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 优惠券
     * */
    public function doCoupon()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];
            $name = $input["name"];
            $full_price = $input["full_price"];
            $face_price = $input["face_price"];
            $use_day = $input["use_day"];

            if (empty($name)) adminReturn(2, "请输入券名称");
            if (empty($full_price)) adminReturn(2, "请输入消费到达金额");
            if (empty($face_price)) adminReturn(2, "请输入面值");
            if (empty($use_day)) adminReturn(2, "请输入有效期（天）");

            if ($full_price < 0) adminReturn(2, "消费到达金额不能小于0");
            if ($face_price < 0) adminReturn(2, "面值不能小于0");
            if ($use_day < 0) adminReturn(2, "有效期不能小于0");
            if ($full_price < $face_price) adminReturn(2, "消费到达金额不能小于面值");
            if (!preg_match("/^[1-9][0-9]*$/", $use_day)) adminReturn(2, "有效期只能是正整数");

            $data = [
                "name" => $name,
                "full_price" => $full_price,
                "face_price" => $face_price,
                "use_day" => $use_day,
            ];

            if ($id > 0) {
                $res = Db::name('mini_coupon')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑优惠券成功', url('couponList'));
                } else {
                    adminReturn(2, '编辑优惠券失败或未编辑');
                }
            } else {
                $data["create_time"] = time();
                $res = Db::name('mini_coupon')->insert($data);
                if ($res) {
                    adminReturn(1, '新增优惠券成功', url('couponList'));
                } else {
                    adminReturn(2, '新增优惠券失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('mini_coupon')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '优惠券');

            return $this->view->fetch();
        }
    }

    /**
     *删除优惠券
     */
    public function delCoupon()
    {
        $id = Request()->param('id');
        if (empty($id)) adminReturn(2, '参数丢失');
        $res_de_coupon = Db::name('mini_coupon')->where(['id' => $id])->delete();
        if ($res_de_coupon) {
            adminReturn(1, '删除优惠券成功', url('deCoupon'));
        } else {
            adminReturn(2, '删除优惠券失败');
        }
    }

    /**
     * 领取记录
     * */
    public function getCouponUserList()
    {
        $input = Request()->param();

        $id = $input['id'];
        $status = $input['status'];

        $where['coupon_id'] = $id;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;
        $list = Db::name('mini_user_coupon')->where($where)->order('create_time desc')->paginate()->each(function ($v) {
            $username = Db::name('mini_user')->where(['id' => $v['user_id']])->value('username');
            $v['username'] = $username ? : '';

            switch ($v['status']) {
                case 1:
                    $v['status_desc'] = '待使用';
                    break;
                case 2:
                    $v['status_desc'] = '已使用';
                    break;
                case 3:
                    $v['status_desc'] = '已过期';
                    break;
            }

            return $v;
        });

        $this->assign('list', $list);

        $this->assign('title', '领取记录');

        return $this->fetch();
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('mini_banner')->order('id desc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $type = $input["type"];
            $to_id = $input["to_id"];

            if (empty($img)) adminReturn(2, '请上传banner图');
            if ($type == 1 && empty($to_id)) adminReturn(2, '请选择商品');
            if ($type == 2 && empty($to_id)) adminReturn(2, '请选择文章');

            $data = [
                "img" => $img,
                "type" => $type,
                'to_id' => $to_id
            ];

            if ($id > 0) {
                $res = Db::name('mini_banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $res = Db::name('mini_banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('mini_banner')->where(['id' => $id])->find();

            $goods_list = Db::name('mini_goods')->field('id,name')->select();
            $this->assign('goods_list', $goods_list);
            $this->assign('goods_list_obj', json_encode($goods_list, JSON_UNESCAPED_UNICODE));

            $article_list = Db::name('mini_article')->field('id,title name')->select();
            $this->assign('article_list_obj', json_encode($article_list, JSON_UNESCAPED_UNICODE));

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('mini_banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('mini_banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    public function companyArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'content' => $content,
                'update_time' => $time
            ];

            $res = Db::name('mini_article')->where(['id' => 1])->update($data);
            if ($res) {
                adminReturn(1, '编辑成功');
            } else {
                adminReturn(2, '编辑失败');
            }
        } else {
            $info = Db::name('mini_article')->where(['id' => 1])->find();

            $this->assign('title', '编辑公司介绍');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    public function schoolArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'content' => $content,
                'update_time' => $time
            ];

            $res = Db::name('mini_article')->where(['id' => 2])->update($data);
            if ($res) {
                adminReturn(1, '编辑成功');
            } else {
                adminReturn(2, '编辑失败');
            }
        } else {
            $info = Db::name('mini_article')->where(['id' => 2])->find();

            $this->assign('title', '编辑商学院');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    public function sourceArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'content' => $content,
                'update_time' => $time
            ];

            $res = Db::name('mini_article')->where(['id' => 3])->update($data);
            if ($res) {
                adminReturn(1, '编辑成功');
            } else {
                adminReturn(2, '编辑失败');
            }
        } else {
            $info = Db::name('mini_article')->where(['id' => 3])->find();

            $this->assign('title', '编辑素材库');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $input = Request()->param();

        $status = $input['status'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $order_sn = $input['order_sn'];

        if (!empty($status)) {
            $where["a.status"] = $status;
        }

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        if ($order_sn) $where['a.order_sn'] = ['like', "%${order_sn}%"];

        $where['a.is_pay'] = 1;
        $list = Db::name('mini_order a')->field("a.*,b.nickname")->join('fa_user b', "a.user_id = b.id", "left")->where($where)->order('create_time desc')->paginate()->each(
            function ($v) {
                $v['status_text'] = doOrderStatus($v['status']);

                if ($v['after_status'] == 0) {
                    $v['after_status_text'] = "未售后";
                } elseif ($v['after_status'] == 1) {
                    $v['after_status_text'] = "售后中";
                } elseif ($v['after_status'] == 2) {
                    $v['after_status_text'] = "售后成功";
                } elseif ($v['after_status'] == 3) {
                    $v['after_status_text'] = "售后失败";
                } else {
                    $v['after_status_text'] = "未知";
                }

                if ($v['pay_type'] == 1) {
                    $v['pay_type_text'] = "微信支付";
                } elseif ($v['pay_type'] == 2) {
                    $v['pay_type_text'] = "积分兑换";
                } else {
                    $v['pay_type_text'] = "未知";
                }

                // 预约订单是否现在【开始配送】按钮
                $businessOrderShowSendBtn = $v['is_business'] == 0 || ($v['is_business'] == 1 && isTimeInRange(date('Y-m-d H:i'), $v['arrive_time'])) ? true : false;
                $v['businessOrderShowSendBtn'] = $businessOrderShowSendBtn;

                // 商品信息
                $vice_order_list = Db::name('mini_vice_order')->field('name,count')->where(['order_id' => $v['id']])->select();
                $v['vice_order_list'] = $vice_order_list;

                return $v;
            }
        );

        $this->assign('list', $list);

        $all_pay_price = Db::name('mini_order a')->join('mini_user b', "a.user_id = b.id", "left")->where($where)->sum('pay_price');
        $this->assign('all_pay_price', sprintf('%.2f', $all_pay_price));

        $user_list = Db::name('mini_user')->where(['is_admin' => 0, 'status' => 1])->select();
        $this->assign('user_list', $user_list);

        $this->assign('title', '订单列表');

        return $this->fetch();
    }

    /**
     * 导出订单
     * */
    public function exportOrderList()
    {
        $title = date('YmdHis') . '订单';
        $th = ['ID', '会员昵称', '订单号', '总金额', '支付金额', '预约用餐时间', '收货信息', '订单状态', '售后状态', '创建时间'];
        $td = ['id', 'username', 'order_sn', 'all_price', 'pay_price', 'status_text', 'after_status_text', 'create_time'];

        $input = Request()->param();

        $status = $input['status'];
        $after_status = $input['after_status'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $user_id = $input['user_id'];

        if (!empty($status)) $where["a.status"] = $status;
        if (!empty($after_status)) $where["a.after_status"] = $after_status;

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        if ($user_id) $where['a.user_id'] = $user_id;

        $where['a.is_del'] = 0;
        $where["a.id"] = ["gt", 0];
        $list = Db::name('mini_order a')->field("a.*,b.mobile,b.username")->join('mini_user b', "a.user_id = b.id", "left")->where($where)->order('create_time desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['status_text'] = doOrderStatus($v['status']);

                if ($v['after_status'] == 0) {
                    $v['after_status_text'] = "未售后";
                } elseif ($v['after_status'] == 1) {
                    $v['after_status_text'] = "售后中";
                } elseif ($v['after_status'] == 2) {
                    $v['after_status_text'] = "售后成功";
                } elseif ($v['after_status'] == 3) {
                    $v['after_status_text'] = "售后失败";
                } else {
                    $v['after_status_text'] = "未知";
                }

                if ($v['pay_type'] == 1) {
                    $v['pay_type_text'] = "微信支付";
                } elseif ($v['pay_type'] == 2) {
                    $v['pay_type_text'] = "积分兑换";
                } else {
                    $v['pay_type_text'] = "未知";
                }

                $v['create_time'] = timeFormat($v['create_time']);
            }
        }

        exportExcel($title, $th, $td, $list);
    }

    /**
     * 订单改价
     * */
    public function changePayPrice()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pay_price = $input['pay_price'];

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if ($pay_price < 0) apiReturn(2, '金额输入有误，请重新输入');

        $res = Db::name('mini_order')->where(['id' => $id])->setField('pay_price', $pay_price);
        if ($res) {
            apiReturn(1, '保存成功');
        } else {
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 订单详情
     */
    public function doOrder()
    {
        $id = input("id");
        $order_info = Db::name('mini_order a')->field("a.*,b.mobile,b.username")->where(["a.id" => $id])->join('mini_user b', "a.user_id = b.id", "left")->find();
        $order_vice = Db::name("mini_vice_order")->where(["order_id" => $id])->select();
        foreach ($order_vice as &$vo) {
            $suk_value_arr = explode("-", $vo['sku_id']);
            $suk_name_str = "";
            foreach ($suk_value_arr as $vv) {
                $sku_info = Db::name("mini_goods_sku")->where(["id" => $vv])->find();
                $sku_p_info = Db::name("mini_goods_sku")->where(["id" => $sku_info['pid']])->find();
                $suk_name_str .= $sku_p_info['name'] . ": " . $sku_info['name'] . ";";
            }
            $vo['suk_name_str'] = $suk_name_str;

            /** 查看商品是不是有评论 */
            $is_have = Db::name('mini_goods_comment')->where(["order_id" => $id, "goods_id" => $vv['goods_id']])->value("id");
            if ($is_have) {
                $is_comment = $is_have;
            } else {
                $is_comment = 0;
            }
            $vo['is_comment'] = $is_comment;
        }

        $this->assign('info', $order_info);
        $this->assign('order_vice', $order_vice);

        $this->assign('title', '订单详情');
        return $this->fetch();
    }

    /**
     *商品评论
     */
    public function doComment()
    {
        $input = Request()->param();

        $id = $input["id"];

        if (empty($id)) adminReturn(2, 'ID缺失');

        //查询出评论内容
        $info = Db::name('mini_goods_comment')->where(["id" => $id])->find();

        $info["img_arr"] = explode(",", $info["imgs"]);

        $this->assign('info', $info);
        $this->assign('title', '评论详情');
        return $this->fetch();
    }

    /**
     * 发货
     * */
    public function sendOrder()
    {
        $input = Request()->param();

        $id = $input['id'];
        $shipper_sn = $input['shipper_sn'];
        $shipper_name = $input['shipper_name'];

        if (empty($id)) adminReturn(2, 'ID缺失');
        if (empty($shipper_name)) adminReturn(2, '请输入物流公司');
        if (empty($shipper_sn)) adminReturn(2, '请输入物流单号');

        $res = Db::name('mini_order')->where(['id' => $id])->update(['status' => 2, 'shipper_name' => $shipper_name, 'shipper_sn' => $shipper_sn, 'send_time' => time()]);
        if ($res) {
            adminReturn(1, '发货成功');
        } else {
            adminReturn(2, '发货失败');
        }
    }


    /**
     * 公告列表
     */
    public function msgList()
    {
        $input = Request()->param();

        $title = $input['title'];
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 公告列表
     */
    public function msgListBak()
    {
        $input = Request()->param();

        $title = $input['title'];
        $where["type"] = 3;
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 公告
     */
    public function doMsg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $title = $input["title"];
            $content = $input["content"];

            if (empty($title)) adminReturn(2, "请输入标题");
            if (empty($content)) adminReturn(2, "请填写公告内容");

            if ($id) {
                $data = [
                    'title' => $title,
                    'content' => $content
                ];

                $res = Db::name('msg')->where(['id' => $id])->update($data);
            } else {
                $data = [
                    "user_id" => 0,
                    "title" => $title,
                    "content" => $content,
                    "create_time" => time()
                ];

                $res = Db::name('msg')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '公告成功', url('msgList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '公告失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('msg')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '公告详情' : '新增公告'));

            return $this->view->fetch();
        }
    }

    /**
     * 删除公告
     */
    public function delMsg()
    {
        $input = Request()->param();

        $id = $input["id"];

        if ($id > 0) {
            $res = Db::name('msg')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除公告成功', url('msgList'));
            } else {
                adminReturn(2, '删除公告失败');
            }
        }
    }

    /**
     * 套餐认养协议
     * */
    public function mealArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'content' => $content
            ];

            $count = Db::name('meal_article')->count();

            if ($count > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('meal_article')->where('1 = 1')->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('mealArticle'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('meal_article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('mealArticle'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $count = Db::name('meal_article')->count();
            $info = Db::name('meal_article')->find();

            $this->assign('title', ($count > 0 ? '编辑' : '新增') . '套餐认养协议');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 联系我们
     * */
    public function aboutUs()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            if (empty($content)) adminReturn(2, '请输入内容');


            $data = [
                'content' => $content
            ];

            $res = Db::name('mini_about_us')->where(['id' => 1])->update($data);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败或未编辑');
            }
        }

        $info = Db::name('mini_about_us')->where(['id' => 1])->find();
        $this->assign('info', $info);


        $this->assign('title', '联系我们');
        return $this->fetch();


    }

    /**
     * 意见反馈
     */
    public function feedbackList()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $where["a.id"] = ["gt", "0"];

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('mini_feedback a')->field("a.*,b.username")->join('mini_user b', "a.user_id = b.id", "left")
            ->where($where)->order('a.create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '意见反馈列表');

        return $this->fetch();
    }

    /**
     * 汇总数据
     * */
    public function allCensus()
    {
        $start_time = strtotime(date('Y-m-d'));
        $end_time = $start_time + 24 * 3600 - 1;
        if (!empty($start_time) && empty($end_time)) {
            $today_where["create_time"] = ["egt", $start_time];
        } elseif (empty($start_time) && !empty($end_time)) {
            $today_where["create_time"] = ["elt", $end_time];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $today_where["create_time"] = ['between', [$start_time, $end_time]];
        }


        $where = ['is_pay' => 1, 'status' => ['neq', '7,8']];

        // 今日订单数
        $today_order_count = Db::name('mini_order')->where($today_where)->where($where)->count();
        // 总订单数
        $all_order_count = Db::name('mini_order')->where($where)->count();
        // 今日订单总额
        $today_order_price = Db::name('mini_order')->where($today_where)->where($where)->sum('pay_price');
        // 总订单总额
        $all_order_price = Db::name('mini_order')->where($where)->sum('pay_price');

        $data = [
            'today_order_count' => $today_order_count,
            'all_order_count' => $all_order_count,
            'today_order_price' => $today_order_price,
            'all_order_price' => $all_order_price,
        ];

        $this->assign('title', '汇总数据');
        $this->assign('info', $data);

        return $this->view->fetch();
    }

    /**
     * 订单统计
     * */
    public function orderCensus()
    {
        $where = ['is_pay' => 1, 'status' => ['neq', '7,8']];
        $time_list = Db::name('mini_order')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->where($where)->order('time asc')->select();
        $order_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $time_where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('mini_order')->where($time_where)->where($where)->count();
                $order_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('order_list', json_encode($order_list));

        $this->assign('title', '订单统计');

        return $this->fetch();
    }

    /**
     * 客户统计
     * */
    public function userCensus()
    {
        $time_list = Db::name('mini_customer')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->where($where)->order('time asc')->select();
        $user_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('mini_customer')->where($where)->count();
                $user_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('user_list', json_encode($user_list));

        $this->assign('title', '客户统计');

        return $this->fetch();
    }

    /**
     * 销售统计
     * */
    public function salesCensus()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $user_id = $input['user_id'];

        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
            $price_where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
            $price_where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
            $price_where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        if ($user_id) {
            $where['user_id'] = $user_id;
            $price_where['a.user_id'] = $user_id;
        }
        $all_goods_pay_price = Db::name('mini_order a')->join('mini_user b', "a.user_id = b.id", "left")->where($price_where)->where(['a.is_pay' => 1])->sum('pay_price');
        $this->assign('all_goods_pay_price', sprintf('%.2f', $all_goods_pay_price));

        $time_list = Db::name('mini_order')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)
            ->where(['is_pay' => 1, 'status' => ['neq', '7,8']])
            ->where($where)
            ->order('time asc')->select();

        $order_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $order_where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];
                unset($where['create_time']);

                $order_pay_price = Db::name('mini_order')->where(['is_pay' => 1, 'status' => ['neq', '1,7,8']])->where($where)->where($order_where)->sum('pay_price');
                $order_list[] = $order_pay_price;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('order_list', json_encode($order_list));

        $user_list = Db::name('mini_customer c')->field('u.id,u.username')->join('mini_user u', 'c.user_id = u.id', 'left')->select();
        $this->assign('user_list', $user_list);

        $this->assign('title', '销售统计');

        return $this->fetch();
    }
}
